#!/bin/sh
cd "${0%/*}" || exit 1    # Run from this directory

# Source tutorial run functions
. "$WM_PROJECT_DIR/bin/tools/RunFunctions"

usage () {
    exec 1>&2
    while [ "$#" -ge 1 ]; do echo "$1"; shift; done
    cat <<USAGE

Usage: ${0##*/} [OPTIONS]
options:
  -c | -cores <nCores>   number of cores in parallel run
  -h | -help             help
  -m | -mesh <S|M|L|XL>  mesh size
                         - S: small, 440k cells
                         - M: medium, 3M cells (default)
                         - L: large, 22.5M cells
                         - XL: extra large, ~200M cells

Runs the ${PWD##*/} simulation

USAGE
    exit 1
}

checkCores () {
    _cores="$1"

    ! [ "$_cores" -eq "$_cores" ] 2> /dev/null && \
        echo "Number of cores '$_cores' must be an integer" && \
        return 1

    [ "$_cores" -lt 2 ] && \
        echo "Number of cores '$_cores' must be >= 2" && \
        return 1

    return 0
}

refineBackgroundMesh () {
    _nRefine="$1"
    _r=0
    while [ $_r -lt "$_nRefine" ]
    do
        echo "Refining the background mesh"
        runParallel -a refineMesh -all
        _r=$(( _r + 1 ))
    done
}

setKeyword () {
    _entry="$1"
    _value="$2"
    _file="$3"

    foamDictionary -entry "$_entry" -set "$_value" "$_file" > /dev/null
}

nRefine=1
nCores=8

while [ "$#" -gt 0 ]
do
   case "$1" in
   -c | -cores)
      [ "$#" -ge 2 ] || usage "'$1' option requires an argument"
      nCores=$2
      shift 2
      checkCores "$nCores" || usage
      setKeyword numberOfSubdomains "$nCores" system/decomposeParDict
      ;;
   -h | -help)
      usage
      ;;
   -m | -mesh)
      [ "$#" -ge 2 ] || usage "'$1' option requires an argument"
      mesh=$2
      shift 2
      case "$mesh" in
          S)  nRefine=0 ;;
          M)  ;;
          L)  nRefine=2 ; setKeyword endTime 2000 system/controlDict ;;
          XL) nRefine=3 ; setKeyword endTime 2000 system/controlDict ;;
          *)  usage "Invalid argument '$mesh' to -m|-mesh <S|M|L|XL>." ;;
      esac
      ;;
   -test)
      shift
      ;;
   -*)
      usage "Invalid option '$1'"
      ;;
   *)
      break
      ;;
    esac
done

# START OF MAIN SCRIPT

runApplication blockMesh

runApplication decomposePar -copyZero

refineBackgroundMesh $nRefine

runParallel snappyHexMesh

runParallel checkMesh

runParallel foamRun

# runApplication reconstructPar -latestTime

#------------------------------------------------------------------------------
